package com.jzh.cmhSystem.controller;

import cn.afterturn.easypoi.entity.vo.NormalExcelConstants;
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.view.PoiBaseView;
import com.jzh.cmhSystem.biz.UserAndDetailService;
import com.jzh.cmhSystem.entity.Result;
import com.jzh.cmhSystem.entity.UserAndDetail;
import io.swagger.annotations.Api;
import io.swagger.v3.oas.annotations.Operation;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Member;
import java.util.ArrayList;
import java.util.List;


@Controller
@Api(tags = "Excel导入导出", description = "Excel导入导出")
@RestController
@RequestMapping("/api/excel")
public class ExcelController {


    @Autowired
    private UserAndDetailService userAndDetailService;

    @Operation(summary = "导出会员列表Excel")
    @GetMapping("/export")
    public void export(    @RequestParam(required = false, defaultValue = "") String nickname,
                           @RequestParam(required = false, defaultValue = "") String phone,
                           @RequestParam(required = false, defaultValue = "") String name,
                           HttpServletResponse response) throws IOException {
        List<UserAndDetail> userList = userAndDetailService.getUserListByRoleAndName(nickname, phone, name, "", null);
        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("User Data", "Users"), UserAndDetail.class, userList);

        response.setHeader("Content-Disposition", "attachment;filename=users.xls");
        response.setContentType("application/vnd.ms-excel");
        workbook.write(response.getOutputStream());
    }

    @Operation(summary = "导入会员列表Excel")
    @PostMapping("/import")
    public List<UserAndDetail> importExcel(@RequestParam("file") MultipartFile file) throws Exception {
        ImportParams params = new ImportParams();
        params.setHeadRows(1);
        params.setTitleRows(0);
        List<UserAndDetail> userList = ExcelImportUtil.importExcel(file.getInputStream(), UserAndDetail.class, params);
        // Save userList to database or process it as needed
        return userList;
    }
}